from openai import OpenAI
import os
from pathlib import Path

client = OpenAI(
    base_url="http://localhost:11434/v1",
    api_key="ollama"
)

model = 'deepseek-r1:1.5b'


def read_file(file_path, file_MB=10):
    """读取文件内容并处理常见异常"""
    fileSize = file_MB * 1024 * 1024
    try:
        path = Path(file_path)
        # 检查文件大小
        if path.stat().st_size > fileSize:
            return None, "文件过大（超过 %d MB），请选择小文件" % file_MB

        with open(path, 'r', encoding='utf-8') as f:
            return f.read(), None
    except FileNotFoundError:
        return None, "文件不存在"
    except PermissionError:
        return None, "没有文件读取权限"
    except UnicodeDecodeError:
        return None, "文件编码不支持（请使用UTF-8编码）"
    except Exception as e:
        return None, f"读取文件出错：{str(e)}"


def process_file_analysis(file_path, user_instruction):
    """处理文件分析请求"""
    # 读取文件内容
    content, error = read_file(file_path)
    if error:
        return error

    # 构建分析指令
    prompt = f"""
    用户指令：{user_instruction}
    文件内容：
    ```
    {content}
    ```
    请根据上述内容进行分析：
    """

    # 调用模型
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": prompt}],
        temperature=0.5,
        stream=True
    )

    # 流式输出结果
    print("\n分析结果：", end="")
    for chunk in response:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)
    print()


# 主循环
while True:
    user_input = input("\nYou: ").strip()

    if user_input.lower() in ["exit", "quit"]:
        break

    # 文件分析指令检测（支持两种格式）
    if user_input.startswith("/file ") or "分析文件：" in user_input:
        # 解析文件路径
        if user_input.startswith("/file "):
            file_path = user_input[6:]
        else:
            file_path = user_input.split("分析文件：")[1].strip()

        # 获取用户指令（如果有）
        if "指令：" in file_path:
            file_path, instruction = file_path.split("指令：", 1)
            file_path = file_path.strip()
            instruction = instruction.strip()
        else:
            instruction = "请总结并分析该文件内容"

        process_file_analysis(file_path, instruction)
        continue

    # 普通对话处理
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": user_input}],
        temperature=0.7,
        stream=True
    )

    print("\nDeepSeek: ", end="")
    for chunk in response:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)

print("\n对话已结束")
